package com.bristua.common.controller;

import com.bristua.common.bean.Result;
import com.bristua.common.biz.AliFileUploadBiz;
import com.bristua.common.enums.CommonCode;
import com.bristua.common.model.condition.TIndexImgExample;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by Administrator on 2018/9/23.
 */
@Controller
@Api(value="文件上传",tags={"文件上传"})
public class FileUploadController {

    @Autowired
    private AliFileUploadBiz aliFileUploadBiz;


    @ApiOperation("文件上传")
    @PostMapping(value="/admin/file/upload")
    @ResponseBody
    public Result result(@RequestParam(value = "files") MultipartFile[] files, String fileType){
        Result result = new Result<>();
        try {
            List<String> urls = new ArrayList<>();
            if(files!=null && files.length>0){
                for(MultipartFile file : files){
                    String prefix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
                    System.out.println(prefix);
                    String fileName=getImgName()+"."+prefix;
                    InputStream inputStream = file.getInputStream();
                    String upload = aliFileUploadBiz.upload(inputStream, fileName, Integer.valueOf(fileType));
                    if(upload.contains("::")){
                        String[] split = upload.split("::");
                        urls.add(split[0]);
                        urls.add(split[1]);
                    }else{
                        urls.add(upload);
                    }

                    inputStream.close();

                }
                result.setMsg(CommonCode.UPLOAD_SUCCESS.getMsg());
                result.setCode(CommonCode.UPLOAD_SUCCESS.getCode());
                result.setData(urls);
                return result;
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }


//    public static void main(String[] args) {
////        String abc = "http://absd/ac.jpg";
////        String substring = abc.substring(0, abc.indexOf("."));
//        System.out.println(substring);
//    }
    public  String getImgName(){
        SimpleDateFormat simpleDateFormat;

        simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

        Date date = new Date();

        String str = simpleDateFormat.format(date);

        Random random = new Random();

        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数

        return rannum + str;// 当前时
    }
}
